package com.ipzoe.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.beust.jcommander.internal.Lists;
import com.ipzoe.act.domain.Activity;
import com.ipzoe.act.service.IActivityService;
import com.ipzoe.cms.domain.Article;
import com.ipzoe.cms.domain.Banner;
import com.ipzoe.cms.domain.StartPage;
import com.ipzoe.cms.enums.StartPageAppEnum;
import com.ipzoe.cms.enums.StartPageStatusEnum;
import com.ipzoe.cms.service.IArticleService;
import com.ipzoe.cms.service.IBannerService;
import com.ipzoe.cms.service.IStartPageService;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.system.service.IRegionService;
import com.ipzoe.system.service.ISysConfigService;
import com.ipzoe.web.convert.ActivityConvert;
import com.ipzoe.web.core.i18n.I18nUtil;
import com.ipzoe.web.model.ActivityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/")
public class IndexController extends WebBaseController {

    private static final String START_PAGE_COOKIE_NAME = "dan_sp_show";

    @Autowired
    private IBannerService iBannerService;
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private IRegionService iRegionService;
    @Autowired
    private IStartPageService startPageService;

    @GetMapping("")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){

        //banner
        LambdaQueryWrapper<Banner> bannerLwq = new LambdaQueryWrapper<>();
        bannerLwq.in(Banner::getLocation, 2,4)
                .eq(Banner::getUseFlag, 1)
                .orderByAsc(Banner::getOrderNum);
        List<Banner> banners = iBannerService.list(bannerLwq);
        List<Banner> location2List;
        Banner location4Banner = null;
        if(CollUtil.isNotEmpty(banners)){
            Map<Integer, List<Banner>> locationMap = banners.parallelStream().collect(Collectors.groupingBy(Banner::getLocation));
            location2List = locationMap.get(2);
            List<Banner> location4List = locationMap.get(4);
            if(CollUtil.isNotEmpty(location4List)){
                location4Banner = location4List.parallelStream().sorted(Comparator.comparing(Banner::getId).reversed()).collect(Collectors.toList()).get(0);
            }
        }else{
            location2List = Lists.newArrayList();
        }
        model.addAttribute("banners", location2List);
        model.addAttribute("topBanner", location4Banner);

        //新闻资讯
        LambdaQueryWrapper<Article> articleLwq = new LambdaQueryWrapper<>();
        articleLwq.eq(Article::getCategoryId, 1).orderByAsc(Article::getOrderNum).last("limit 10");
        List<Article> articles = iArticleService.list(articleLwq);
        model.addAttribute("articles", articles);

        //健康贴士
        LambdaQueryWrapper<Article> articleLwq2 = new LambdaQueryWrapper<>();
        articleLwq2.eq(Article::getCategoryId, 5).orderByAsc(Article::getOrderNum).last("limit 3");
        List<Article> articles2 = iArticleService.list(articleLwq2);
        model.addAttribute("articles2", articles2);

        //潜水事故报告
        LambdaQueryWrapper<Article> articleLwq4 = new LambdaQueryWrapper<>();
        articleLwq4.eq(Article::getCategoryId, 4).orderByAsc(Article::getOrderNum).last("limit 3");
        List<Article> articles4 = iArticleService.list(articleLwq4);
        model.addAttribute("articles4", articles4);

        //常见问题
        LambdaQueryWrapper<Article> articleLwq3 = new LambdaQueryWrapper<>();
        articleLwq3.eq(Article::getCategoryId, 6).orderByAsc(Article::getOrderNum).last("limit 3");
        List<Article> articles3 = iArticleService.list(articleLwq3);
        model.addAttribute("articles3", articles3);

        LambdaQueryWrapper<Activity> activityLqw = new LambdaQueryWrapper<>();
        activityLqw.orderByDesc(Activity::getCreateTime).last("limit 8");
        List<Activity> activityList = iActivityService.list(activityLqw);
        List<ActivityVO> activityVOList = ActivityConvert.INSTANCE.convert(activityList);
        activityVOList.forEach(r->{
            r.setCity(iRegionService.getById(r.getCityCode()));
        });
        model.addAttribute("activityList", activityVOList);

        String email = iSysConfigService.selectConfigByKey("email.contact");
        model.addAttribute("email", email);

        //startpage
        boolean showed = false;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (START_PAGE_COOKIE_NAME.equals(cookie.getName())) {
                    showed = true;
                    break;
                }
            }
        }
        if(!showed){
            LambdaQueryWrapper<StartPage> lqw = new LambdaQueryWrapper<>();
            lqw.eq(StartPage::getApp, StartPageAppEnum.PC_WEB.getCode())
                    .eq(StartPage::getStatus, StartPageStatusEnum.ENABLE.getCode())
                    .last("limit 1");
            StartPage startPage = startPageService.getOne(lqw);
            if(ObjectUtil.isNull(startPage)){
                model.addAttribute("showStartPage", false);
            }else{
                model.addAttribute("showStartPage", true);
                model.addAttribute("startPage", startPage);

                Cookie startpageCookie = new Cookie(START_PAGE_COOKIE_NAME, String.valueOf(System.currentTimeMillis()));
                startpageCookie.setMaxAge(-1);
                response.addCookie(startpageCookie);
            }
        }else{
            model.addAttribute("showStartPage", false);
        }

        return getLocaleHtml("index.html", request);
    }

    @ResponseBody
    @GetMapping("/lang/{lang}")
    public AjaxResult lang(@PathVariable String lang, HttpServletResponse response){
        I18nUtil.setLocaleToCookie(lang, response);
        return AjaxResult.success();
    }


}
